LeetCode 16. 3Sum Closest
题意
Given an array S of n integers, find three integers in S such that the sum is closest to a given number, target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
For example, given array S = {-1 2 1 -4}, and target = 1.
The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
与[LeetCode 15. 3Sum]类似,只不过这里a b c和的目标值变成了变量,求与目标变量最接近的那个a b c的和。
思路
[LeetCode 15. 3Sum]中要求a+b+c=0,而这里则是a+b+c=target,因此在枚举确定a+b后只需要把[LeetCode 15. 3Sum]中算法的二分搜索目标由-c改为target-c即可。
具体实现时可以使用stl::lower_bound()函数来找大于等于c-target的第一个数,找到后根据返回的情况判断这个数周围的一个数是否可能成为更优解,注意检查周围可能的更优解时访问不要越界。
代码
|
|